const express = require('express')
const db = require('../db/db')
const expect = require('../extensions/expect')
const filter = require('../extensions/filter')

const router = express.Router()


router.get('/answer/:id', filter.signin, (req, res) => {
    db.Question.getById(req.params.id)
        .then(question => {
            res.render('answer', question)
        })
        .catch(err => {
            res.pageError(err)
        })
})


router.post('/api/answer/add/:id', (req, res) => {
    new db.Answer.Model({
        text: req.body.text,
        question: req.params.id,
        createUser: req.cookies.user.id,
        createTime: new Date(),
        ip: db.formatIP(req.ip)
    })
        .save()
        .then(model => {
            var answer = db.toData(model)
            return db.Question.Model.findOneAndUpdate(
                { _id: req.params.id },
                { $push: { answers: answer.id } }
            ).exec()
        })
        .then(() => {
            res.apiSuccess('提交回答成功！')
        })
        .catch(err => {
            if (err && err.errors && err.errors.text) {
                res.apiMessage(err.errors.text.message)
            }
            else {
                res.apiError(err)
            }
        })
})


router.post('/api/answer/remove/:id', filter.signin, (req, res) => {
    db.Answer.Model.findById({ _id: req.params.id })
        .then(m => {
            expect(m).not.toBeNull().error('要删除的回答不存在！')

            var hasPermission = m.createUser == req.cookies.user.id || req.cookies.user.account == 'admin'
            expect(hasPermission).toBe(true).error('没有删除这个回答的权限！')
            
            return db.Question.Model.update(
                { _id: m.question },
                { $pull: { answers: req.params.id } }
            ).exec()
        })
        .then(() => {
            res.apiSuccess('删除回答成功！')
        })
        .catch(err => {
            res.apiError(err)
        })
})


module.exports = router